<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Contract extends MX_Controller
{
    function __construct()
    {
        parent::__construct();
        
        $this->load->model('Contract_model', '', TRUE);
        $this->load->model('Phase_model', '', TRUE);

        $this->properti = $this->property->get();
        $this->acl->otentikasi();

        $this->modul = $this->components->get(strtolower(get_class($this)));
        $this->title = strtolower(get_class($this));

        $this->load->library('currency');
        $this->customer = $this->load->library('customer');
        $this->user = $this->load->library('admin');
    }

    private $properti, $modul, $title;
    private $customer,$user;

    function index()
    { $this->get_last_contract();}

    function get_last_contract()
    {
        $this->acl->otentikasi1($this->title);

        $data['title'] = $this->properti['name'].' | Administrator  '.ucwords($this->modul['title']);
        $data['h2title'] = $this->modul['title'];
        $data['main_view'] = 'contract_view';
	$data['form_action'] = site_url($this->title.'/search');
        $data['link'] = array('link_back' => anchor('main/','<span>back</span>', array('class' => 'back')));
        
	$uri_segment = 3;
        $offset = $this->uri->segment($uri_segment);

	// ---------------------------------------- //
        $contracts = $this->Contract_model->get_last_contract($this->modul['limit'], $offset)->result();
        $num_rows = $this->Contract_model->count_all_num_rows();

        if ($num_rows > 0)
        {
	    $config['base_url'] = site_url($this->title.'/get_last_contract');
            $config['total_rows'] = $num_rows;
            $config['per_page'] = $this->modul['limit'];
            $config['uri_segment'] = $uri_segment;
            $this->pagination->initialize($config);
            $data['pagination'] = $this->pagination->create_links(); //array menampilkan link untuk pagination.
            // akhir dari config untuk pagination
            

            // library HTML table untuk membuat template table class zebra
            $tmpl = array('table_open' => '<table cellpadding="2" cellspacing="1" class="tablemaster">');

            $this->table->set_template($tmpl);
            $this->table->set_empty("&nbsp;");

            //Set heading untuk table
            $this->table->set_heading('No', 'Code', 'Cur', 'Customer', 'Period', 'Notes', 'Amount', '#', 'Action');

            $i = 0 + $offset;
            foreach ($contracts as $contract)
            {
                $datax = array('name'=> 'cek[]','id'=> 'cek'.$i,'value'=> $contract->id,'checked'=> FALSE, 'style'=> 'margin:0px');
                
                $this->table->add_row
                (
                    ++$i, 'CO-00'.$contract->no, $contract->currency, $contract->prefix.' '.$contract->name, tglin($contract->dates).' / '.tglin($contract->due), $contract->notes, number_format($contract->amount,2,",","."), $this->get_phase_count($contract->id),
                    anchor($this->title.'/confirmation/'.$contract->id,'<span>update</span>',array('class' => $this->post_status($contract->id), 'title' => 'edit / update')).' '.
                    anchor($this->title.'/add_trans/'.$contract->no,'<span>details</span>',array('class' => 'update', 'title' => '')).' '.
                    anchor($this->title.'/delete/'.$contract->id.'/'.$contract->no,'<span>delete</span>',array('class'=> 'delete', 'title' => 'delete' ,'onclick'=>"return confirm('Are you sure you will delete this data?')"))
                );
            }

            $data['table'] = $this->table->generate();
        }
        else
        {
            $data['message'] = "No $this->title data was found!";
        }

        // Load absen view dengan melewatkan var $data sbgai parameter
	$this->load->view('template', $data);
    }

    function search()
    {
        $this->acl->otentikasi1($this->title);

        $data['title'] = $this->properti['name'].' | Administrator Find '.ucwords($this->modul['title']);
        $data['h2title'] = 'Find '.$this->modul['title'];
        $data['main_view'] = 'contract_view';
	$data['form_action'] = site_url($this->title.'/search');
        $data['link'] = array('link_back' => anchor('contract/','<span>back</span>', array('class' => 'back')));

        $contracts = $this->Contract_model->search($this->input->post('tno'), $this->input->post('tcust'), 
                                                   $this->input->post('tdate'), $this->input->post('tdue'))->result();
        
        $tmpl = array('table_open' => '<table cellpadding="2" cellspacing="1" class="tablemaster">');

        $this->table->set_template($tmpl);
        $this->table->set_empty("&nbsp;");

        //Set heading untuk table
        $this->table->set_heading('No', 'Code', 'Cur', 'Customer', 'Period', 'Notes', 'Amount', '#', 'Action');

        $i = 0;
        foreach ($contracts as $contract)
        {
            $datax = array('name'=> 'cek[]','id'=> 'cek'.$i,'value'=> $contract->id,'checked'=> FALSE, 'style'=> 'margin:0px');

            $this->table->add_row
            (
                ++$i, 'CO-00'.$contract->no, $contract->currency, $contract->prefix.' '.$contract->name, tglin($contract->dates).' / '.tglin($contract->due), $contract->notes, number_format($contract->amount,2,",","."), $this->get_phase_count($contract->id),
                anchor($this->title.'/confirmation/'.$contract->id,'<span>update</span>',array('class' => $this->post_status($contract->id), 'title' => 'edit / update')).' '.
                anchor($this->title.'/add_trans/'.$contract->no,'<span>details</span>',array('class' => 'update', 'title' => '')).' '.
                anchor($this->title.'/delete/'.$contract->id.'/'.$contract->no,'<span>delete</span>',array('class'=> 'delete', 'title' => 'delete' ,'onclick'=>"return confirm('Are you sure you will delete this data?')"))
            );
        }
        
        $data['table'] = $this->table->generate();
        $this->load->view('template', $data);
    }

//    ===================== approval ===========================================

    private function post_status($val)
    {
       $val = $this->Phase_model->get_free_phase($val);
       if ($val > 0) {$class = "notapprove"; }
       else{$class = "approve"; }
       return $class;
    }

    function confirmation($pid){ redirect($this->title); }

    function delete($uid,$po)
    {
        $this->acl->otentikasi_admin($this->title);

        $this->Phase_model->delete_po($po); // model to delete contract item
        $this->Contract_model->delete($uid);

        $this->session->set_flashdata('message', "1 $this->title can't removed, contract approved..!");
        redirect($this->title);
    }

    private function cek_confirmation($po,$page=null)
    {
       $val = $this->Contract_model->get_contract_by_no($po)->row();
       if ($val->status == 1)
       {
          $this->session->set_flashdata('message', "1 $this->title can't removed, contract approved..!");
          if ($page){ redirect($this->title.'/'.$page.'/'.$po.'/'); } else { redirect($this->title); }  
       }
    }

    function add()
    {
        $this->acl->otentikasi2($this->title);

        $data['title'] = $this->properti['name'].' | Administrator '.ucwords($this->modul['title']);
        $data['h2title'] = 'Create New '.$this->modul['title'];
	$data['form_action'] = site_url($this->title.'/add_process');
        $data['currency'] = $this->currency->combo();
        $data['code'] = $this->Contract_model->counter();
        $data['user'] = $this->session->userdata("username");
        
        $this->load->view('contract_form', $data);
    }

    function add_process()
    {
        $this->acl->otentikasi2($this->title);

        $data['title'] = $this->properti['name'].' | Administrator  '.ucwords($this->modul['title']);
        $data['h2title'] = $this->modul['title'];
        $data['main_view'] = 'contract_form';
	$data['form_action'] = site_url($this->title.'/add_process');
	$data['currency'] = $this->currency->combo();
        $data['code'] = $this->Contract_model->counter();
        $data['user'] = $this->session->userdata("username");

	// Form validation
        $this->form_validation->set_rules('tcust', 'Customer', 'required|callback_valid_customer');
        $this->form_validation->set_rules('tno', 'CO - No', 'required|numeric|callback_valid_no');
        $this->form_validation->set_rules('tdate', 'Invoice Date', 'required');
        $this->form_validation->set_rules('tdue', 'Due Date', 'required');
        $this->form_validation->set_rules('ccurrency', 'Currency', 'required');
        $this->form_validation->set_rules('tnote', 'Note', 'required');
        $this->form_validation->set_rules('tuser', 'User', 'required');

        if ($this->form_validation->run($this) == TRUE)
        {
            $contract = array('customer' => $this->customer->get_customer_id($this->input->post('tcust')), 'no' => $this->input->post('tno'),
                              'dates' => $this->input->post('tdate'), 'due' => $this->input->post('tdue'),  'currency' => $this->input->post('ccurrency'),
                              'notes' => $this->input->post('tnote'), 'user' => $this->user->get_userid($this->input->post('tuser')), 'log' => $this->session->userdata('log'));

            $this->Contract_model->add($contract);
            $this->session->set_flashdata('message', "One $this->title data successfully saved!");
            redirect($this->title.'/add_trans/'.$this->input->post('tno'));

//            echo 'true';
        }
        else
        {
              $this->load->view('contract_form', $data);
//            echo validation_errors();
        }

    }

    function add_trans($po=null)
    {
        $this->acl->otentikasi2($this->title);

        $data['title'] = $this->properti['name'].' | Administrator '.ucwords($this->modul['title']);
        $data['h2title'] = 'Create New '.$this->modul['title'];
	$data['form_action'] = site_url($this->title.'/update_process/'.$po);
        $data['form_action_item'] = site_url($this->title.'/add_item/'.$po);
        $data['currency'] = $this->currency->combo();
        $data['code'] = $po;
        $data['user'] = $this->session->userdata("username");

        $contract = $this->Contract_model->get_contract_by_no($po)->row();

        $data['default']['customer'] = $this->customer->get_customer_shortname($contract->customer);
        $data['default']['date'] = $contract->dates;
        $data['default']['due'] = $contract->due;
        $data['default']['currency'] = $contract->currency;
        $data['default']['note'] = $contract->notes;
        $data['default']['user'] = $this->user->get_username($contract->user);
        $data['default']['balance'] = number_format($contract->amount,2,",",".");

//        ============================ Purchase Item  =========================================
        $items = $this->Phase_model->get_last($po)->result();

        // library HTML table untuk membuat template table class zebra
        $tmpl = array('table_open' => '<table cellpadding="2" cellspacing="1" class="tablemaster">');

        $this->table->set_template($tmpl);
        $this->table->set_empty("&nbsp;");

        //Set heading untuk table
        $this->table->set_heading('No', 'Date', 'Amount', 'Action');

        foreach ($items as $item)
        {
            $this->table->add_row
            (
                $item->no, tgleng($item->dates), number_format($item->amount,2,",","."),
                anchor($this->title.'/delete_item/'.$item->id.'/'.$po,'<span>delete</span>',array('class'=> 'delete', 'title' => 'delete' ,'onclick'=>"return confirm('Are you sure you will delete this data?')"))
            );
        }

        $data['table'] = $this->table->generate();
        
        $this->load->view('contract_transform', $data);
    }

//    ======================  Item Transaction   ===============================================================

    function add_item($po=null)
    {
        $this->cek_confirmation($po,'add_trans');
        
        $this->form_validation->set_rules('tpart', 'Part', 'required|numeric');
        $this->form_validation->set_rules('tpartdate', 'Part Date', 'required');
        $this->form_validation->set_rules('tpartamount', 'Amount', 'required|numeric');

        if ($this->form_validation->run($this) == TRUE)
        {
            $pitem = array('no' => $this->input->post('tpart'), 'contract' => $po, 'dates' => $this->input->post('tpartdate'),
                           'amount' => $this->input->post('tpartamount'), 'status' => 0);
            $this->Phase_model->add($pitem);
            $this->update_trans($po);

            echo 'true';
        }
        else{   echo validation_errors(); }
    }

    private function update_trans($po)
    {
        $totals = $this->Phase_model->total($po);
        $contract = array('amount' => $totals['amount']);
	$this->Contract_model->update($po, $contract);
    }

    function delete_item($id,$po)
    {
        $this->cek_confirmation($po,'add_trans');
        $this->acl->otentikasi2($this->title);
        
        $this->Phase_model->delete($id); // memanggil model untuk mendelete data
        $this->update_trans($po);
        $this->session->set_flashdata('message', "1 phase successfully removed..!"); // set flash data message dengan session
        redirect($this->title.'/add_trans/'.$po);
    }
//    ==========================================================================================

    // Fungsi update untuk mengupdate db
    function update_process($po=null)
    {
        $this->acl->otentikasi2($this->title);

        $data['title'] = $this->properti['name'].' | Administrator  '.ucwords($this->modul['title']);
        $data['h2title'] = $this->modul['title'];
	$data['form_action'] = site_url($this->title.'/update_process');
	$data['link'] = array('link_back' => anchor('contract/','<span>back</span>', array('class' => 'back')));

	// Form validation
        $this->form_validation->set_rules('tcust', 'Customer', 'required');
        $this->form_validation->set_rules('tno', 'CO - No', 'required|numeric|callback_valid_contract');
        $this->form_validation->set_rules('tdate', 'Invoice Date', 'required');
        $this->form_validation->set_rules('tdue', 'Due Date', 'required');
        $this->form_validation->set_rules('ccurrency', 'Currency', 'required');
        $this->form_validation->set_rules('tnote', 'Note', 'required');
        $this->form_validation->set_rules('tuser', 'User', 'required');

        if ($this->form_validation->run($this) == TRUE)
        {
            $contract = array('customer' => $this->customer->get_customer_id($this->input->post('tcust')),
                              'dates' => $this->input->post('tdate'), 'due' => $this->input->post('tdue'),  'currency' => $this->input->post('ccurrency'), 'status' => 1,
                              'notes' => $this->input->post('tnote'), 'user' => $this->user->get_userid($this->input->post('tuser')), 'log' => $this->session->userdata('log'));

            $this->Contract_model->update($po, $contract);
//            $this->session->set_flashdata('message', "One $this->title has successfully updated!");
//            redirect($this->title.'/add_trans/'.$po);
            echo 'true';
        }
        else
        {
//            $this->load->view('contract_transform', $data);
            echo validation_errors();
        }
    }

    private function get_phase_count($val)
    {
        $val = $this->Phase_model->get_last($val)->num_rows();
        return $val;
    }

    public function valid_customer($name)
    {
        if ($this->customer->valid_customer($name) == FALSE)
        {
            $this->form_validation->set_message('valid_customer', "Invalid Customer.!");
            return FALSE;
        }
        else
        {
            return TRUE;
        }
    }

    public function valid_contract($val)
    {
        $val = $this->Contract_model->get_contract_by_no($val)->row();
        if ($val->status == 1)
        {
            $this->form_validation->set_message('valid_contract', "Contract Approved.!");
            return FALSE;
        }
        else { return TRUE; }
    }

    public function valid_no($no)
    {
        if ($this->Contract_model->valid_no($no) == FALSE)
        {
            $this->form_validation->set_message('valid_no', "Order No already registered.!");
            return FALSE;
        }
        else {  return TRUE; }
    }


}

?>